package com.yusysqdy.gulimail.member.interceptor;

import com.yusysqdy.common.constant.AuthServerConstant;
import com.yusysqdy.common.vo.MemberRsepVo;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @program: gulimail
 * @contact: qindy0116@126.com
 * @author: Mr.DYQin
 * @create: 2021-02-24 11:12
 * @Description:
 **/

@Configuration
public class LoginUserInterceptor implements HandlerInterceptor {

    public static ThreadLocal<MemberRsepVo> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String uri = request.getRequestURI();
        // 这个请求直接放行
        boolean match = new AntPathMatcher().match("/member/**", uri);
        if (match) {
            return true;
        }
        HttpSession session = request.getSession();
        MemberRsepVo memberRsepVo = (MemberRsepVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (memberRsepVo != null) {
            threadLocal.set(memberRsepVo);
            return true;
        } else {
            // 没登陆就去登录
            session.setAttribute("msg", AuthServerConstant.NOT_LOGIN);
            response.sendRedirect("http://auth.gulimallserver.com/login.html");
            return false;
        }
    }
}
